package com.cn.netty.http.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.*;

@Slf4j
public class HttpServer {

  public static void main(String[] args) {

    ThreadFactory guavaThreadFactory = new BasicThreadFactory.Builder().namingPattern("ycy-").build();

    ExecutorService exec = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(10),guavaThreadFactory );
    exec.submit(() -> {
      log.info("--记忆中的颜色是什么颜色---");
    });


    EventLoopGroup boss = new NioEventLoopGroup(1,guavaThreadFactory);
    EventLoopGroup work = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap();
    ServerBootstrap serverBootstrap = bootstrap.group(boss, work)

//    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
//
//    ServerBootstrap bootstrap = new ServerBootstrap();
//    ServerBootstrap serverBootstrap = bootstrap.group(eventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .localAddress(9999).childHandler(
                    new ChannelInitializer<SocketChannel>() {
                      @Override
                      protected void initChannel(SocketChannel ch) throws Exception {
                        log.warn("SocketChannel -> {}", ch);

                        ch.pipeline().addLast(new LoggingHandler());

                        ch.pipeline().addLast("decode", new HttpRequestDecoder()); //解码请求体
                        ch.pipeline().addLast("encode", new HttpResponseEncoder()); //编码请求体

                        ch.pipeline().addLast("agg", new HttpObjectAggregator(1 * 1024)); // 聚合成完成的http报文
                        ch.pipeline().addLast(new BusinessHandler());

                      }
                    });
    try {
      ChannelFuture sync = serverBootstrap.bind().sync();
      sync.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}
